package cpu.footprint.ui;

import android.app.Dialog;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMGroup;
import com.squareup.picasso.Picasso;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cpu.footprint.R;
import cpu.footprint.adapter.CommonAdapter;
import cpu.footprint.bean.BaseBean;
import cpu.footprint.bean.Group;
import cpu.footprint.bean.ListViewItem;
import cpu.footprint.adapter.ViewHolder;
import cpu.footprint.api.ApiUrl;
import cpu.footprint.api.LocalStorage;
import cpu.footprint.api.MyApplication;
import cpu.footprint.api.ResultMessage;
import cpu.footprint.bean.User;
import cpu.footprint.api.APIService;
import cpu.footprint.api.RespCallBack;
import cpu.footprint.util.CreateDialogUtil;
import cpu.footprint.util.DateUtils;
import cpu.footprint.util.FileUtil;
import cpu.footprint.view.XListView;

/**
 * Created by Administrator on 2017/3/11.
 */
@ContentView(R.layout.fragment_group)
public class GroupFragment extends Fragment implements XListView.IXListViewListener {
    @ViewInject(R.id.title_back)
    public ImageView title_back;//点击弹出左侧滑
    @ViewInject(R.id.title_content)
    public TextView title_content;//标题栏内容
    @ViewInject(R.id.title_menu_text)
    public TextView title_menu_text;//标题栏文字功能
    @ViewInject(R.id.title_menu_image)
    public ImageView title_menu_image;//标题栏图形功能
    @ViewInject(R.id.title_menu_image2)
    public ImageView title_menu_image2;//标题栏图形功能
    @ViewInject(R.id.listview_group)
    private XListView listView_group;
    @ViewInject(R.id.text_group_nologin)
    private TextView text_group_nologin;
    private List<EMGroup> grouplist=new ArrayList<EMGroup>();
    private List<Group> list=new ArrayList<Group>();
    private ArrayList<ListViewItem> mList;
    private User user=new User();
    private Dialog mDialog;
    private CommonAdapter<ListViewItem> groupadapter;//群组适配器
    private MyApplication myApplication;
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (mDialog != null) {
                if (mDialog.isShowing())
                    mDialog.dismiss();
            }
            switch (msg.what) {
                case ResultMessage.GET_INFO_SUCCESS: {
                    String jsonStr = msg.obj.toString();
                    user=null;
                    LocalStorage.saveUserModel(getActivity(),user);
                    initData();
                }
                break;
                case ResultMessage.GET_INFO_FAILED: {
                    CreateDialogUtil.ToastShow(getActivity(),"身份验证失败，请重新登录！");
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    intent.putExtra("IsLogin",false);
                    startActivity(intent);
                    getActivity().finish();
                }
                break;
                case ResultMessage.GET_GROUPS_SUCCESS:
                    String jsonStr = (String) msg.obj;
                    list= JSON.parseArray(jsonStr,
                            Group.class);
                    mList.clear();
                    onLoad();
                    DealWithData();
                    groupadapter.notifyDataSetChanged();
                    break;
                case ResultMessage.GET_GROUPS_FAILED:
                    CreateDialogUtil.ToastShow(getActivity(),msg.obj.toString());
                    break;
                case ResultMessage.GET_IMGROUP_SUCCESS:
                    initAdapter();
                    //adapter.notifyDataSetChanged();
                    break;
                case ResultMessage.GET_IMGROUP_FAILED:
                    String message = msg.obj.toString();
                    Toast.makeText(getActivity(),"获取群组失败: "+message,Toast.LENGTH_SHORT).show();
                    break;
                case ResultMessage.FAILED:
                    CreateDialogUtil.ToastShow(getActivity(),"连接失败");
                    break;
                case ResultMessage.TIMEOUT:
                    CreateDialogUtil.ToastShow(getActivity(),"连接超时");
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = x.view().inject(this, inflater, container);
        initViewAndLister(view);
        if(myApplication.isLogin()) {
            text_group_nologin.setVisibility(View.GONE);
            listView_group.setVisibility(View.VISIBLE);
            initData();
            // 初始化数据
            mList = new ArrayList<ListViewItem>();
            initAdapter();
            FileUtil.flag = 0;
        }else{
            text_group_nologin.setVisibility(View.VISIBLE);
            listView_group.setVisibility(View.GONE);
            CreateDialogUtil.ToastShow(getActivity(),"未登录");
        }
        return view;
    }
    /**
     * 初始化控件和监听
     * @param view
     */
    private void initViewAndLister(final View view) {
        title_back.setImageResource(R.mipmap.menu);
        title_menu_text.setVisibility(View.GONE);
        title_menu_image.setVisibility(View.GONE);
        title_menu_image2.setVisibility(View.VISIBLE);
        title_menu_image2.setImageResource(R.mipmap.add);
        title_content.setText("群组");
        listView_group.setPullLoadEnable(false);
        listView_group.setPullRefreshEnable(true);
        listView_group.setXListViewListener(this);
        mDialog=CreateDialogUtil.CreateDialog(getActivity(), "数据加载中...",mHandler);
        listView_group.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                Group model=new Group();
                try {
                    model=mList.get(position-1).getGroup();
                    Intent intent = new Intent(getActivity(), TalkActivity.class);
                    intent.putExtra("chatToName", model.getName());
                    intent.putExtra("groupId", model.getId());
                    intent.putExtra("sqlId", model.getSqlId());
                    startActivityForResult(intent, 1);
                    getActivity().overridePendingTransition(0,R.anim.fade);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        title_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity activity= (MainActivity) getActivity();
                activity.leftNavChange();//侧滑栏状态切换
            }
        });
        title_menu_image2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(),GroupSearchActivty.class);
                startActivityForResult(intent,2);
                getActivity().overridePendingTransition(0,R.anim.fade);
            }
        });
    }
    /**
     * 初始化数据
     */
    private void initData() {
        myApplication= (MyApplication) getActivity().getApplication();
        if(!myApplication.isLogin()||myApplication.getUser()==null){
            Toast.makeText(getActivity(),"请先登录",Toast.LENGTH_SHORT).show();
            Intent intent=new Intent(getActivity(),LoginActivity.class);
            intent.putExtra("IsLogin",false);
            startActivity(intent);
            getActivity().overridePendingTransition(0,R.anim.fade);
            getActivity().finish();
        }else{
            requestData();
        }
    }
    /**
     * 刷新数据
     */
    private void refresh(){

    }
    /**
     * 处理获取的数据
     */
    private void DealWithData() {
        mList.clear();
        if(list.size()<=0){
            text_group_nologin.setVisibility(View.VISIBLE);
            text_group_nologin.setText("暂未参与任何群组");
            return;
        }
        ListViewItem item=new ListViewItem();
        item.setmType(1);
        item.setmContent("我参与的群");
        mList.add(item);
        for(Group model:list){
            if(model.getActiveId()==user.getCurrentlyActiveId()&&model.getActiveId()!=null){
                item=new ListViewItem();
                item.setmType(2);
                item.setGroup(model);
                mList.add(item);
            }
        }
        if(mList.get(mList.size()-1).getmType()==1){
            mList.remove(mList.size()-1);
        }
        item=new ListViewItem();
        item.setmType(1);
        item.setmContent("我创建的群");
        mList.add(item);
        for(Group model:list){
            if(model.getOwner().equals(user.getMobilePhone())){
                item=new ListViewItem();
                item.setmType(2);
                item.setGroup(model);
                mList.add(item);
            }
        }
        if(mList.get(mList.size()-1).getmType()==1){
            mList.remove(mList.size()-1);
        }
        item=new ListViewItem();
        item.setmType(1);
        item.setmContent("我加入的群");
        mList.add(item);
        for(Group model:list){
            if(!model.getOwner().equals(user.getMobilePhone())){
                item=new ListViewItem();
                item.setmType(2);
                item.setGroup(model);
                mList.add(item);
            }
        }
        if(mList.get(mList.size()-1).getmType()==1){
            mList.remove(mList.size()-1);
        }
        initAdapter();
    }
    /**
     *
     * 初始化群组的适配器
     *
     */
    private void initAdapter() {
        groupadapter = new CommonAdapter<ListViewItem>(getActivity(), mList,
                R.layout.group_item) {
            @Override
            public void convert(ViewHolder helper, ListViewItem item,
                                int position) {
                LinearLayout item_groupType=helper.getView(R.id.item_groupType);
                LinearLayout item_group=helper.getView(R.id.item_group);
                item_groupType.setVisibility(View.GONE);
                item_group.setVisibility(View.GONE);
                if(item.getmType()==2){
                    //群组内容
                    item_group.setVisibility(View.VISIBLE);
                    LinearLayout item_groupLayout=helper.getView(R.id.item_groupLayout);
                    item_groupLayout.setMinimumHeight(50);
                    helper.setText(R.id.text_groupNumber,item.getGroup().getId()+"");
                    helper.setText(R.id.text_groupName,
                            item.getGroup().getName());
                    helper.setImageResource(R.id.image_groupHeadPic,R.mipmap.head);
                    ImageView imageView=helper.getView(R.id.image_groupHeadPic);
                    Picasso.with(getActivity()).load(ApiUrl.URL_HOST + item.getGroup().getHeadpicture()).placeholder(R.mipmap.head).into(imageView);
                }else{
                    //我创建的群（主题）
                    item_groupType.setVisibility(View.VISIBLE);
                    LinearLayout item_groupLayout=helper.getView(R.id.item_groupLayout);
                    item_groupLayout.setMinimumHeight(35);
                    helper.setText(R.id.text_groupType,item.getmContent());
                }
            }
        };
        listView_group.setAdapter(groupadapter);
        groupadapter.notifyDataSetChanged();
    }

    @Override
    public void onRefresh() {
        requestData();
    }

    private void requestData() {
        user=myApplication.getUser();
        Map<String,String> map=new HashMap<String,String>();
        map.put("mobilePhone", user.getMobilePhone());
        map.put("token", user.getToken());
        APIService.Post(ApiUrl.URL_LIST_GROUP,map,new RespCallBack<BaseBean<Group>>(getActivity()){
            @Override
            public void onSuccess(BaseBean<Group> result) {
                super.onSuccess(result);
                if(result.success){
                    list=result.datas;
                    onLoad();
                    DealWithData();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }
        });
    }

    @Override
    public void onLoadMore() {

    }
    /**
     * 停止刷新
     */
    private void onLoad() {
        listView_group.stopRefresh();
        listView_group.stopLoadMore();
        listView_group.setRefreshTime(DateUtils.dateToString(new Date()));
    }
}
